module spi_slave(
    input  clk,
    input  rst_n,
    input  sclk,
    input  ss_n,
    input  mosi,
    output reg miso
);
    
    reg clkr;
    reg [1:0] clks;
    reg [7:0] dreg, dbuf;
    
    //时钟信号判断
    always @(posedge clk, negedge rst_n)
    begin
        if (!rst_n) begin
            clkr <= 1'b0;
            clks <= 2'b0;
        end
        else begin
            clkr <= sclk;
            clks[0] <= clkr & (!sclk);
            clks[1] <= (!clkr) & sclk;
        end 
    end 
    
    //数据接收控制
    always @(posedge clk, negedge rst_n)
    begin
        if (!rst_n) begin
            dbuf <= 8'b0;
        end
        else begin
            if ((!ss_n)&clks[0]) begin
                dbuf <= {dbuf[6:0], mosi};
            end
        end 
    end 
    
    //数据发送控制
    always @(posedge clk, negedge rst_n) begin
        if (!rst_n) begin
            miso <= 1'b0;
            dreg <= 8'hC6;
        end
        else begin
            if ((!ss_n)&clks[1]) begin
                miso <= dreg[7];
                dreg <= {dreg[6:0], 1'b0};
            end
            else if (ss_n) begin
                miso <= 1'b0;
            end 
        end
    end 
    
endmodule 